<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Crypt;
use EasyWeChat\Factory;

class LoginController extends Controller
{
    //注册用户
    public function DoRegister(Request $request)
    {
        //获取请求参数
        $openid = $request->post('openid');
        $phone = $request->post('phone');
        $code = $request->post('code');
        $password = $request->post('password');

        //判断数据
        if(empty($phone)) {
            return ['code' => 0, 'message' => '缺少手机号', 'data' => ''];
        }
        if(empty($code)) {
            return ['code' => 0, 'message' => '缺少短信验证码', 'data' => ''];
        }
        if(empty($openid) || empty($password)) {
            return ['code' => 0, 'message' => '缺少必要参数', 'data' => ''];
        }

        //判断用户是否存在
        $user = DB::table('users')->where('phone', $phone)->first();
        if(!empty($user)) {
            return ['code' => 0, 'message' => '用户已注册', 'data' => ''];
        }

        //短信验证码判断
        $message = DB::table('messages')->where('mobile', $phone)->where('is_use', '0')->orderBy('send_at', 'desc')->first();
        if(empty($message)) {
            return ['code' => 0, 'message' => '短信验证码已使用', 'data' => ''];
        }
        if(time() > strtotime($message->overdue_at)) {
            return ['code' => 0, 'message' => '短信验证码已过期', 'data' => ''];
        }
        if($message->code != $code) {
            return ['code' => 0, 'message' => '短信验证码不正确', 'data' => ''];
        }
        DB::beginTransaction();
        //添加用户
        $info['phone'] = $phone;
        $info['openid'] = $openid;
        $info['password'] = md5($password);
        $info['created_at'] = date('Y-m-d H:i:s', time());
        $info['updated_at'] = date('Y-m-d H:i:s', time());
        $info['serial_number'] = $this->getSerialNumber();
        $user = DB::table('users')->insertGetId($info);
        if(!$user) {
            DB::rollBack();
            return ['code' => 0, 'message' => '用户注册失败', 'data' => ''];
        }

        $token = Crypt::encryptString($user);
        $res = DB::table('users')->where('id', $user)->update(['remember_token' => $token]);
        if(!$res) {
            DB::rollBack();
            return ['code' => 0, 'message' => '用户注册失败', 'data' => ''];
        }

        //更改短信状态
        DB::table('messages')->where('id', $message->id)->update(['is_use' => 1]);

        DB::commit();
        return ['code' => 1, 'message' => '注册成功', 'data' => $token];
    }

    //登陆操作
    public function DoLogin(Request $request)
    {
        //获取参数
        $openid = $request->post('openid');
        $phone = $request->post('phone');
        $password = $request->post('password');
        $type = $request->post('type');

        switch ($type) {
            case '1':
                if(empty($openid)) {
                    return ['code' => 0, 'message' => '缺少必要参数', 'data' => ''];
                }
                $user = DB::table('users')->where('openid', $openid)->first();
                if(empty($user)) {
                    return ['code' => 0, 'message' => '用户不存在', 'data' => ''];
                }
                break;
            case '2':
                if(empty($phone) || empty($password)) {
                    return ['code' => 0, 'message' => '缺少必要参数', 'data' => ''];
                }
                $user = DB::table('users')->where('phone', $phone)->first();
                if(empty($user)) {
                    return ['code' => 0, 'message' => '用户不存在', 'data' => ''];
                }
                if($user->password != md5($password)) {
                    return ['code' => 0, 'message' => '用户输入密码不正确', 'data' => ''];
                }
                break;
            default:
                return ['code' => 0, 'message' => '登陆参数数据违规', 'data' => ''];
        }

        $token = Crypt::encryptString($user->id);
        $res = DB::table('users')->where('id', $user->id)->update(['remember_token' => $token]);
        if(!$res) {
            return ['code' => 0, 'message' => '登陆失败', 'data' => ''];
        }
        return ['code' => 1, 'message' => '登陆成功', 'data' => $token];
    }

    //获取编号
    public function getSerialNumber()
    {
        $info = randStr(4);
        $user = DB::table('users')->where('serial_number', $info)->first();
        if(!empty($user)) {
            $this->getSerialNumber();
        }
        return $info;
    }

    //小程序 通过code换取登陆信息
    public function miniProgram(Request $request)
    {
        $code = $request->post('code');
        $config = [
            'app_id' => 'wx065aee6c99f8d5cc',
            'secret' => '7ca80d6abdd6352de18ef4483704b21b',

            // 下面为可选项
            'response_type' => 'array',

            'log' => [
                'level' => env('WECHAT_LOG_LEVEL', 'debug'),
                'file' => env('WECHAT_LOG_FILE', storage_path('logs/wechat.log')),
            ],
        ];

        $app = Factory::miniProgram($config);
        $return = $app->auth->session($code);
        return ['code' => 1, 'message' => '请求成功', 'data' => $return];
    }

    //校验用户是否存在
    public function checkUser(Request $request)
    {
        $openid = $request->post('openid');

        $user = DB::table('users')->where('openid', $openid)->value('id');

        if(empty($user)) {
            return 0;
        }else{
            return 1;
        }
    }
}
